package com.qd.p2p.web.action;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.qd.p2p.sina.pay.enums.PayType;
import com.qd.p2p.sina.pay.response.BlankResponse;
import com.qd.p2p.sina.pay.response.CreateHostingDepositResponse;
import com.qd.p2p.sina.service.SinaPayService;
import com.qdlc.p2p.biz.service.AccountBankService;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.util.NotifyRequestUrl;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.exception.AccountException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.MD5Util;
import com.qdlc.p2p.dal.dto.AccountBank;
import com.qdlc.p2p.dal.dto.AccountRecharge;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.AccountRechargeModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 快捷支付（充值）
 * 快捷支付（充值）分为两个步骤：
 * 1. doQuicklyPay()方法，发起支付请求，此时在响应中会获取到ticket、outOrderNo,以及发送到手机上验证码。
 * 2. doPayAdvance()方法，根据ticket和手机验证码进行支付推进，如果响应成功，则处理后续的DB操作，DB操作放入到队列中执行。
 *
 * @author linya 2016-01-04
 */
public class QuickPayAction extends BaseAction<AccountRechargeModel> implements ModelDriven<AccountRechargeModel> {

    private static final Logger log = Logger.getLogger(QuickPayAction.class);

    private AccountRechargeModel model = new AccountRechargeModel();

    @Autowired
    SinaPayService sinaPayService;
    @Resource
    UserIdentifyService userIdentifyService;
    @Resource
    AccountBankService accountBankService;
    
    @Resource
	AccountRechargeService accountRechargeService;

    @Resource
    UserService userService;
    
    @Override
    public AccountRechargeModel getModel() {
        return model;
    }

    /**
     * PT 快捷支付，获取手机验证码
     *
     * @author linya 2016-01-04
     */
    @Action(value = "/member/pay/doQuicklyPay")
    public void doQuicklyPay() throws Exception {
        //获取当前登录用户
    	long userId = getSessionUserId();
        UserIdentify userIdentify = UserUtils.getUserIdentify(userId);
        User user = UserUtils.getUserById(userId);
        //充值前检测基本信息
        try {
            model.validIdentifyForRecharge(userIdentify);
            model.validNewRecharge();
        } catch (AccountException e) {
            throw new AccountException(e.getMessage(), BusinessException.TYPE_JSON);
        }

        //获取绑定的银行卡号（目前平台只支持绑定一张银行卡）
        List<AccountBank> accountBankList = accountBankService.list(user.getUserId());
        if (CollectionUtils.isEmpty(accountBankList)) {
            throw new AccountException("账户没有绑定银行卡，不能进行快捷支付，请先绑定银行卡！", BusinessException.TYPE_JSON);
        }
        AccountBank accountBank = accountBankList.get(0);

        //绑卡支付
        String identityId = UserUtils.getUserTppCustId(user.getUserId());
        if(StringUtils.isBlank(identityId)){
        	throw new AccountException("请进行实名认证，开通第三方托管账户!", BusinessException.TYPE_JSON);
        }
        double amount = model.getMoney();
        String cardId = accountBank.getTppCardId();
        log.info(MessageFormat.format("++++[快捷支付][获取验证码]{0}打算充值{1}元", user, amount));
        CreateHostingDepositResponse response = sinaPayService.bindingPay(identityId, amount, cardId, "绑卡支付", NotifyRequestUrl.QUICK_PAY_NOTIFY_URL);
        Map<String, Object> extraMap = new HashMap<String, Object>();
        if (response == null
                || !com.qd.p2p.sina.pay.Constant.SUCCESS.equals(response.getReqStatus())) {
            extraMap.put("result", false);
            extraMap.put("msg", "系统正繁忙！请稍候重试！");
            printWebJson(getStringOfJpaObj(extraMap));
        } else if (response.success()) {
            String ticket = response.getTicket();
            String orderId = response.getOutTradeNo();
            String tickets = MD5Util.MD5Encode(ticket + orderId + amount, "utf-8");
            extraMap.put("ticket", ticket);
            extraMap.put("orderId", orderId);
            extraMap.put("tickets", tickets);
            printWebResult("获取验证码成功", true, extraMap);
        } else {
            printWebResult("获取验证码失败，请尝试重新获取！", false);
        }
    }

    /**
     * PT 快捷支付，支付推进
     *
     * @author linya 2016-01-04
     */
    @Action(value = "/member/pay/doPayAdvance", results = {@Result(name = "result", type = "redirect", location = "/tpp/tppSinaAction/tppRechargeReturn.html")})
    public String doPayAdvance() throws Exception {
        //出现异常，返回的URL
        String exceptionUrl = "/member/recharge/newRecharge.html";
        //这里的token名称兼容以前的充值功能
        checkToken("newRecharge", exceptionUrl);
        //从请求参数中获取手机验证码和ticket
        String validCode = request.getParameter("code");
        String ticket = request.getParameter("ticket");
        String orderId = request.getParameter("orderId");
        double money = model.getMoney();
        String tickets = request.getParameter("tickets");
        //从缓存中获取ticket、订单号、充值金额
        if (StringUtils.isBlank(validCode)) {
            throw new AccountException("验证码不能为空!", exceptionUrl);
        } else if (StringUtils.isBlank(ticket)) {
            throw new AccountException("请重新获取验证码!", exceptionUrl);
        }

        String checkTicket = MD5Util.MD5Encode(ticket + orderId + money, "utf-8");
        if (!checkTicket.equals(tickets)) {
            throw new AccountException("非法请求,请重新获取验证码！", exceptionUrl);
        }
        User user = getSessionUser();
        //快捷支付推进，如果成功，则删除缓存值，并将支付任务放入队列中
        BlankResponse response = sinaPayService.payAdvance(ticket, validCode, NotifyRequestUrl.QUICK_PAY_NOTIFY_URL);
        log.info(MessageFormat.format("++++[快捷支付][确认支付]{0}充值{1}元{2}!", user, money, response.success() ? "成功" : "失败"));

        if (response == null
                || !com.qd.p2p.sina.pay.Constant.SUCCESS.equals(response.getReqStatus())) {
            throw new AccountException("系统正繁忙！请稍候重试！", exceptionUrl);
        } else if (response.success()) {
            // 保存充值记录 (待处理状态，等待回调处理)
    		AccountRecharge ar = new AccountRecharge(orderId, user, money, PayType.binding_pay.getType(), Constant.TPP_NAME);
    		ar.setStatus(AccountRechargeModel.RECHARGE_UNTREATED);
    		accountRechargeService.add(ar);
        } else {
            throw new AccountException(response.getResponseMessage(), exceptionUrl);
        }
        return "result";
    }

}
